package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.Result;
import com.example.demo.entity.pojo.Card;
import com.example.demo.entity.pojo.Student;
import com.example.demo.entity.pojo.Token;
import com.example.demo.entity.vo.CostRecordVo;
import com.example.demo.entity.vo.StudentVo;
import com.example.demo.exception.LoginException;
import com.example.demo.service.CardService;
import com.example.demo.service.CostRecordService;
import com.example.demo.service.StudentService;
import com.example.demo.utils.token.TokenDuration;
import com.example.demo.utils.token.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping(value = "/user" )
@CrossOrigin

public class StudentController {
    @Autowired
    CardService cardService;

    @Autowired
    StudentService studentService;

    @Autowired
    CostRecordService costRecordService;
//    /**
//     * 登录方法
////     * @param account 账号
////     * @param password 密码
//     * @return
//     */
//    @PostMapping("/login")
//    @ResponseBody
//    public Result login(@RequestBody String json, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest){
//        httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type");
//        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("origin"));
//        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST,GET");
//        httpServletResponse.addHeader("Access-Control-Expose-Headers","Token");
//        //@RequestBody 传送的数据格式为json
//        JSONObject jsonObject = JSONObject.parseObject(json);
//        String account = jsonObject.get("account").toString();
//        String password = jsonObject.get("password").toString();
//        if (account == "" || account.equals("") || password == "" || password.equals("")){
//            return Result.error("账号或密码不能为空");
//        }
//        Student student = studentService.login(account);
//        if (student == null){
//            return Result.error("用户不存在");
//        }
//        if (!student.getPassword().equals(password)){
//            return Result.error("账号或密码错误");
//        }
//        Token token = new Token(student.getId(),student.getState(), TokenDuration.DEFAULTDURATION);
////        System.out.println(token.getExTime());
////        System.out.println(System.currentTimeMillis());
//        String strToken = TokenUtil.createNewTokenBytoken(token);
//        httpServletResponse.setHeader("Token",strToken);
//        return Result.ok("登录成功");
//    }


    /**
     * 登录方法
     //     * @param account 账号
     //     * @param password 密码
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public Result login(String account,String password, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest){
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST,GET");
        httpServletResponse.addHeader("Access-Control-Expose-Headers","Token");
        //@RequestBody 传送的数据格式为json
//        JSONObject jsonObject = JSONObject.parseObject(json);
//        String account = jsonObject.get("account").toString();
//        String password = jsonObject.get("password").toString();
        if (account == "" || account.equals("") || password == "" || password.equals("")){
            return Result.error("账号或密码不能为空");
        }
        Student student = studentService.login(account);
        if (student == null){
            return Result.error("用户不存在");
        }
        if (!student.getPassword().equals(password)){
            return Result.error("账号或密码错误");
        }
        Token token = new Token(student.getId(),student.getState(), TokenDuration.DEFAULTDURATION);
//        System.out.println(token.getExTime());
//        System.out.println(System.currentTimeMillis());
        String strToken = TokenUtil.createNewTokenBytoken(token);
        httpServletResponse.setHeader("Token",strToken);
        Result result = Result.ok("登录成功");
        result.setData(student.getName());
        return result;

    }


    /**
     * 获取个人信息
     * @return
     */
    @GetMapping("/getMessage")
    @ResponseBody
    @CrossOrigin
    public Result getMessage(HttpServletRequest httpServletRequest) throws LoginException {
        String id = (String) httpServletRequest.getAttribute("id");
        int id1 = Integer.parseInt(id);
//        System.out.println(id1);
        StudentVo message = studentService.getMessage(id1);
        if (message == null){
            return Result.error("查询失败");
        }
        Result result = Result.ok("查询成功");
        result.setData(message);
        return result;
    }

    /**
     * 充值
     * @param money 金额
     * @return
     */
    @GetMapping("/recharge")
    @ResponseBody
    public Result recharge(double money,HttpServletRequest httpServletRequest){
        if (money <= 0){
            return Result.error("充值金额需要大于0");
        }
        String id = (String) httpServletRequest.getAttribute("id");
        int id1 = Integer.parseInt(id);
        int i = studentService.recharge(id1,money);
        if (i > 0){
            return Result.ok("充值成功");
        }
        return Result.error("充值失败");
    }

    /**
     * 借书
     * @return
     */
    @GetMapping("/borrowBook")
    @ResponseBody
    public Result borrowBook(int bookId,HttpServletRequest httpServletRequest) throws LoginException {
        String id = (String) httpServletRequest.getAttribute("id");
        int id1 = Integer.parseInt(id);
        StudentVo message = studentService.getMessage(id1);
        int cardId = message.getCardId();
        if(cardId == 0){
            return Result.error("请先办卡");
        }
        Card message1 = cardService.getMessage(message.getCardId());
        if (message1.getState() == 0){
            return Result.error("卡被冻结，借书失败");
        }
        if (studentService.borrowBook(cardId,bookId)) {
            return Result.ok("借书成功");
        }
        return Result.error("借书失败");

    }

    /**
     * 修改密码
     * @param newPassword
     * @param oldPassword
     * @return
     */
    @GetMapping("/modifyPassword")
    @ResponseBody
    public Result modifyPassword(String newPassword,String oldPassword,HttpServletRequest httpServletRequest){
        String id = httpServletRequest.getAttribute("id")+"";
        int Id = Integer.parseInt(id);
        boolean b = studentService.modifyPassword(Id, newPassword, oldPassword);
        if (b){
            return Result.ok("修改成功");
        }
        return Result.error("修改失败");
    }


    /**
     * 查看流水纪录
     * @param httpServletRequest
     * @param type
     * @return
     */
    @GetMapping("/getCostRecord")
    @ResponseBody
    public Result getCostRecord(HttpServletRequest httpServletRequest,int type) throws LoginException {
        Object id = httpServletRequest.getAttribute("id");
        int id1 = Integer.parseInt(id+"");
        StudentVo message = studentService.getMessage(id1);
        List<CostRecordVo> record = costRecordService.getRecord(message.getCardId(), type);
        if (record.size() == 0){
            return Result.ok("没有纪录");
        }
        Result result = Result.ok("查看成功");
        result.setData(record);
        return result;
    }


    /**
     * 还书
     * @param id 书籍id
     * @return
     */
    @GetMapping("/returnBook")
    @ResponseBody
    public Result returnBook(int id,HttpServletRequest httpServletRequest) throws LoginException {
        String str = httpServletRequest.getAttribute("id")+"";
        int sid = Integer.parseInt(str);
        int cardId = studentService.getMessage(sid).getCardId();
        String s = studentService.returnBook(cardId, id);
        if (s.equals("归还失败")){
            return Result.error(s);
        }
        return Result.ok(s);

    }


    /**
     * 注册
     * @param account
     * @param password
     * @param sex
     * @param name
     * @param age
     * @param gardeNumber
     * @return
     */
    @GetMapping("/register")
    @ResponseBody
    public Result register(String account,String password,String sex,String name,String age,String gardeNumber,HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse){
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST,GET");
        httpServletResponse.addHeader("Access-Control-Expose-Headers","Token");

        if (sex == null || account == null || password == null || name == null  || age == null || gardeNumber == null) {
            return Result.error("注册失败 信息不全!");
        }
        //查询账号是否存在
        if (studentService.getMessageByAccount(account,gardeNumber ) != null) {
            return Result.error("注册失败 用户名或学号重复!");
        }
        //可以注册
        if (studentService.register(account,password,sex,age,name,gardeNumber)) {
            return Result.ok("注册成功");
        }
        return Result.error("注册失败");

    }





    /**
     * 判断是否登录
     * @return
     */
    @GetMapping("/exist")
    @ResponseBody
    public Result exist(HttpServletRequest httpServletRequest){
        String token = httpServletRequest.getHeader("Token");
        if (token == "" || token.equals("")){
            return Result.error("未登录");
        }
        if (!TokenUtil.checkOverTime(token)) {
            return Result.ok("已登录");
        }
        return Result.error("未登录");
    }



    @PostMapping("/r")
    @ResponseBody
    public Result r(@RequestBody String json ,HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws LoginException {
//        System.out.println(json);
        JSONObject jsonObject = JSONObject.parseObject(json);
//        System.out.println(jsonObject.getString("account"));
//        String id = httpServletRequest.getParameter("id");
//        System.out.println(id);
//        if (id.equals("1") || id == "1"){
//            Result result = Result.ok("请求成功");
//            StudentVo message = studentService.getMessage(Integer.parseInt(id));
//            result.setData(message);
//            return result;
//        }
        return Result.error("请求失败");
    }
}
